package com.lagou.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.*;

@Activate(group = {CommonConstants.CONSUMER})
public class HomeWorkFilter implements Filter {

    Map<String,List<Long>> map= new HashMap<>();

    public HomeWorkFilter(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                for (Map.Entry<String, List<Long>> entry : map.entrySet()) {
                    Collections.sort(map.get(entry.getKey()));
                    float percent90 = 0.90f;
                    float percent99 = 0.99f;
                    int index90 = (int)(percent90 * map.get(entry.getKey()).size() - 1);
                    int index99 = (int)(percent99 * map.get(entry.getKey()).size() - 1);
                    System.out.println(entry.getKey()+":TP90:"+map.get(entry.getKey()).get(index90) + "ms");
                    System.out.println(entry.getKey()+":TP99:"+map.get(entry.getKey()).get(index99) + "ms");
                }
                System.out.println("================");
            }
        },60000,5000);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {


        long startTime = System.currentTimeMillis();
        try{
            //执行方法
            invocation.getMethodName();
            return invoker.invoke(invocation);
        }finally {
            List<Long> longs = map.get(invocation.getMethodName());
            if(longs==null||longs.size()==0){
                List<Long> times = new ArrayList<>();
                times.add(System.currentTimeMillis()-startTime);
                map.put(invocation.getMethodName(),times);
            }else{
                map.get(invocation.getMethodName()).add(System.currentTimeMillis()-startTime);
            }
        }
    }
}
